#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QFileDialog>
#include<QThread>
#include <QImage>
#include <QBuffer>
#include "camerahandler.h"  // 必须包含完整定义
#include "videosender.h"
#include "videorecver.h"
#include "sockethelper.h"
#include "meetingmanager.h"


MainWindow::MainWindow(QTcpSocket *socket,QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->socket=socket;
    //用户主界面相关
    this->window_init();
    this->readSettings();
    connect(ui->stackedWidget, &QStackedWidget::currentChanged,
                this, &MainWindow::updateNavButtons);


    this->updateList_timer=new QTimer(this);
    connect(this->updateList_timer,&QTimer::timeout,this,&MainWindow::on_updateList);
    this->updateList_timer->start(3000);

    //当前聊天对象变化
    connect(ui->contactList, &QListWidget::currentItemChanged,this, &MainWindow::onCurrentChanged);

    //组相关

    connect(ui->group_list_w, &QListWidget::itemClicked, this, &MainWindow::on_groupListClicked);

    // 请求讨论组列表
    MessagePackage pack;
    pack.setType("group_list");
    pack.setUserName(client_user);
    MessagePackage::sendMessage(pack, socket);

    //列表刷新函数
    QTimer *groupRefreshTimer = new QTimer(this);
        connect(groupRefreshTimer, &QTimer::timeout, [this](){
            MessagePackage pack;
            pack.setType("group_list");
            pack.setUserName(client_user);
            MessagePackage::sendMessage(pack,this->socket);
        });
        groupRefreshTimer->start(9000);

        ui->horizontalSlider->hide();
        //会议相关
        connect(ui->pushButton_createMeeting, &QPushButton::clicked, this, &MainWindow::createMeeting);
        connect(ui->pushButton_joinMeeting, &QPushButton::clicked, this, &MainWindow::joinMeeting);

        connect(socketHelper::getInstance(), &socketHelper::meetingCreated,this, &MainWindow::onMeetingCreated);
        connect(socketHelper::getInstance(), &socketHelper::meetingJoined,this, &MainWindow::onMeetingJoined);




}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::getClient_user() const
{
    return client_user;
}

void MainWindow::setClient_user(const QString &value)
{
    client_user = value;
    this->setWindowTitle(QString("欢迎 %1 使用会议系统！").arg(value));
}

void MainWindow::on_recvSingleMessage(MessagePackage &pack)
{
    ui->contactNameLabel->setText(pack.userName());
    ui->chatHistory->append(QString("<b>%1</b>: %2").arg(pack.userName()).arg(pack.getMessage()));
}

void MainWindow::closeEvent(QCloseEvent *close_ev)
{
    emit this->mainQuit();
    QSettings settings;
    settings.setValue("lastPage", ui->stackedWidget->currentIndex());
//    close_ev->ignore();
    if (thread && thread->isRunning()) {
        recver->endTask();
        thread->requestInterruption(); // 设置中断标志
        thread->quit();                // 退出事件循环
        thread->wait(1000);            // 等待最多1秒
    }
//    thread->terminate();
    close_ev->accept();
    QMainWindow::closeEvent(close_ev);

}

void MainWindow::on_quit_pb_triggered()
{
    emit this->mainQuit();
}

void MainWindow::window_init()
{

    ui->send_pb->hide();
    ui->recv_pb->hide();
    actChat = new QAction(QIcon(":/icons/chat.png"), "通信", this);
    actMeeting = new QAction(QIcon(":/icons/meeting.png"), "会议", this);
    actFile = new QAction(QIcon(":/icons/file.png"), "文件", this);

    // 添加到工具栏
    ui->toolbarMain->addAction(actChat);
    ui->toolbarMain->addAction(actMeeting);
    ui->toolbarMain->addAction(actFile);

    // 连接信号槽
    connect(actChat, &QAction::triggered, [=](){
        ui->stackedWidget->setCurrentWidget(ui->pageChat);
    });
    connect(actMeeting, &QAction::triggered, [=](){
        ui->stackedWidget->setCurrentWidget(ui->pageMeeting);
    });
    connect(actFile, &QAction::triggered, [=](){
        ui->stackedWidget->setCurrentWidget(ui->pageFile);
    });

    // 设置工具栏样式（参考需求3.3界面布局）
    ui->toolbarMain->setStyleSheet(
        "QToolBar { background: #f5f5f5; border: none; }"
        "QToolButton { padding: 12px; font-size: 25px; }"
        "QToolButton:hover { background: #e0e0e0; }"
    );

    // 确保视频窗口占比≥70%（需求3.3）
    ui->pageMeeting->setMinimumSize(QSize(0, ui->centralwidget->height() * 0.7));

    ui->toolbarMain->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); // 图标+文字
    ui->toolbarMain->setIconSize(QSize(470,60)); // 统一图标大小

    // 强制工具栏允许扩展
    QLayout* toolbarLayout = ui->toolbarMain->layout();
    if (toolbarLayout) {
        toolbarLayout->setSpacing(0);
        toolbarLayout->setContentsMargins(0, 0, 0, 0);
    }

    // 添加伸缩间隔（关键）
    ui->toolbarMain->addSeparator();
    ui->toolbarMain->insertWidget(actChat, new QWidget()); // 左侧伸缩
    ui->toolbarMain->addWidget(new QWidget()); // 右侧伸缩
}

// 初始化时恢复
void MainWindow::readSettings()
{
    QSettings settings;
    int lastPage = settings.value("lastPage", 0).toInt();
    ui->stackedWidget->setCurrentIndex(lastPage);
}
void MainWindow::updateNavButtons(int index)
{
    // 更新图标状态
    actChat->setIcon(index == 0 ?
        QIcon(":/icons/chat_active.png") : QIcon(":/icons/chat.png"));
    actMeeting->setIcon(index == 1 ?
        QIcon(":/icons/meeting_active.png") : QIcon(":/icons/meeting.png"));
    actFile->setIcon(index == 2 ?
                         QIcon(":/icons/file_active.png") : QIcon(":/icons/file.png"));
}

void MainWindow::on_updateList()
{
    MessagePackage pack;
    pack.setType("update");
    MessagePackage::sendMessage(pack,this->socket);
    ui->contactList->clear();
}

void MainWindow::update_onlUser(QString name)
{
    ui->contactList->addItem(name);
}


//void MainWindow::on_sendButton_clicked()
//{
//    QString message=ui->messageInput->toPlainText();
//    if(message.isEmpty()) return;
//    QString receiver= ui->contactNameLabel->text();
//    MessagePackage pack;
//    pack.setType("single");
//    pack.setUserName(this->client_user);
//    pack.setRecvName(receiver);
//    pack.setMessage(message);
//    MessagePackage::sendMessage(pack,this->socket);
//    ui->chatHistory->append(QString("<b>我</b>: %1").arg(message));
//    ui->messageInput->clear();
//}

void MainWindow::onCurrentChanged()
{
    QListWidgetItem *currentItem = ui->contactList->currentItem();
    if(currentItem)
    {
        this->isGroupChat=0;
        ui->contactNameLabel->setText(currentItem->text());
        ui->chatHistory->clear();
    }
    else
    {
        return;
    }
}

//void MainWindow::on_add_group_clicked()
//{
//    QInputDialog dialog(this);
//    dialog.setWindowTitle("新建讨论组");
//    dialog.setLabelText("输入讨论组名称:");
//    if(dialog.exec() == QDialog::Accepted && !dialog.textValue().isEmpty())//点击了确认 并且不空
//    {
//        MessagePackage pack;
//        pack.setType("group_create");
//        pack.setGroupName(dialog.textValue());
//        pack.setUserName(client_user); // 设置创建者
//        MessagePackage::sendMessage(pack, socket);
//    }
//}
//void MainWindow::updateGroupList(const QJsonArray& groups)
//{
//    ui->group_list_w->clear();
//    for(const auto& group : groups)
//    {
//        QListWidgetItem* item = new QListWidgetItem(QIcon(":/icons/group.png"),group.toObject()["name"].toString());
//        item->setData(Qt::UserRole, group.toObject()["id"].toString());
//        ui->group_list_w->addItem(item);
//    }
//}
void MainWindow::on_add_group_clicked()
{
    QString groupName = QInputDialog::getText(this, "新建讨论组", "输入讨论组名称:");
        if (groupName.isEmpty()) return;

        // 2. 输入成员列表（用逗号分隔）
        QString membersStr = QInputDialog::getText(this, "添加成员", "输入要邀请的成员（用逗号分隔）:");
        QStringList members = membersStr.split(",", Qt::SkipEmptyParts);

        // 3. 发送创建请求
        MessagePackage pack;
        pack.setType("group_create");
        pack.setGroupName(groupName);
        pack.setUserName(client_user);
        pack.setMemberList(members);  // 设置成员列表
        MessagePackage::sendMessage(pack, socket);
}

void MainWindow::on_groupListReceived(const QJsonArray &groups)
{
    qDebug()<<"群组 列表到达槽 函数 ";
    updateGroupList(groups);
}

void MainWindow::updateGroupList(const QJsonArray &groups)
{
    ui->group_list_w->clear();
    //ui->group_list_w->addItem("===我的群组=====");
    for(const auto& group : groups)
    {
        QJsonObject groupObj = group.toObject();
        QListWidgetItem* item = new QListWidgetItem(
            QIcon(":/icons/group.png"),
            groupObj["name"].toString());
        item->setData(Qt::UserRole, groupObj["id"].toString());
        ui->group_list_w->addItem(item);
    }
}

void MainWindow::on_groupListClicked(QListWidgetItem *item)
{
    currentGroupId = item->data(Qt::UserRole).toString();
    isGroupChat = true;
    ui->contactNameLabel->setText(item->text() + " (群聊)");
    ui->chatHistory->clear();
}

void MainWindow::on_groupMessageReceived(MessagePackage &pack)
{
    if(pack.groupId() == currentGroupId)
    {
        ui->chatHistory->append(
            QString("<b>%1</b>: %2").arg(pack.userName()).arg(pack.getMessage()));
    }
}

void MainWindow::on_groupJoined(bool success, const QString &groupId, const QString &groupName)
{
    Q_UNUSED(groupId);
    if(success)
    {
        QMessageBox::information(this, "加入讨论组", QString("成功加入讨论组: %1").arg(groupName));

        // 更新讨论组列表
        MessagePackage pack;
        pack.setType("group_list");
        pack.setUserName(client_user);
        MessagePackage::sendMessage(pack, socket);
    }
    else
    {
        QMessageBox::warning(this, "加入讨论组", "加入讨论组失败");
    }
}

void MainWindow::on_groupMemberAdded(const QString &groupId, const QString &username)
{
    if(groupId == currentGroupId)
    {
        ui->chatHistory->append(
            QString("<i>系统: 用户 %1 加入了讨论组</i>").arg(username));
    }
}

void MainWindow::on_sendButton_clicked()
{
    QString message = ui->messageInput->toPlainText();
    if(message.isEmpty()) return;

    if(isGroupChat && !currentGroupId.isEmpty())
    {
        // 发送群消息
        MessagePackage pack;
        pack.setType("group_message");
        pack.setGroupId(currentGroupId);
        pack.setUserName(client_user);
        pack.setMessage(message);
        MessagePackage::sendMessage(pack, socket);

        ui->chatHistory->append(QString("<b>我</b>: %1").arg(message));
//        ui->chatHistory->append(
//            QString("<p style='margin: 4px; text-align: right;'>"
//                    "<span style='background: #e0f0ff; border-radius: 8px; padding: 6px;'>"
//                    "%1 :<b>我</b>"
//                    "</span></p>"
//            ).arg(message)
//        );
    }
    else
    {
        // 发送私聊消息
        QString receiver = ui->contactNameLabel->text();
        MessagePackage pack;
        pack.setType("single");
        pack.setUserName(client_user);
        pack.setRecvName(receiver);
        pack.setMessage(message);
        MessagePackage::sendMessage(pack, socket);

//        ui->chatHistory->append(
//            QString("<p style='margin: 4px; text-align: right;'>"
//                    "<span style='background: #e0f0ff; border-radius: 8px; padding: 6px;'>"
//                    "%1 :<b>我</b>"
//                    "</span></p>"
//            ).arg(message)
//        );
        ui->chatHistory->append(QString("<b>我</b>: %1").arg(message));
    }

    ui->messageInput->clear();
}
void MainWindow::onGroupCreated(bool success, const QString &groupId, const QString &groupName)
{
    qDebug() << "创建结果回调:" << success;
    if(success) {
        MessagePackage pack;
                pack.setType("group_list");
                pack.setUserName(client_user);
                MessagePackage::sendMessage(pack, socket);
        // 3. 更新UI
        QListWidgetItem* item = new QListWidgetItem(QIcon(":/icons/group.png"), groupName);
        item->setData(Qt::UserRole, groupId);
        ui->group_list_w->addItem(item);

        // 可选：自动选中新建的组
        //ui->group_list_w->setCurrentItem(item);
    }
}

void MainWindow::on_btnRefresh_clicked()
{
    MessagePackage pack;
        pack.setType("file_list_req");
        MessagePackage::sendMessage(pack, socket);
}

void MainWindow::on_btnUpload_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "选择文件");
        if(path.isEmpty()) return;

        QFile file(path);
        if(file.open(QIODevice::ReadOnly))
        {
            MessagePackage pack;
            pack.setType("file_upload");
            pack.setGroupName(QFileInfo(file).fileName()); // 文件名
            pack.setMessage(file.readAll().toBase64());    // 内容Base64编码
            MessagePackage::sendMessage(pack, socket);
            file.close();
        }
}

void MainWindow::on_bunDownload_clicked()
{
    QListWidgetItem* item = ui->listFiles->currentItem();
    if(!item) return;

    QString filename = item->data(Qt::UserRole).toString(); // 文件名存储在UserRole
    QString savePath = QFileDialog::getSaveFileName(this, "保存文件", filename);

    if(!savePath.isEmpty())
    {
        qDebug() << "保存路径：" << savePath;
        MessagePackage pack;
        pack.setType("file_download");
        pack.setGroupName(filename);
        pack.setMessage(savePath); // 将完整路径作为消息内容发送
        MessagePackage::sendMessage(pack, socket);
    }
}
// 文件列表更新槽函数
//void MainWindow::onFileListReceived(const QJsonArray &files)
//{
//    qDebug()<<"该显示了";
//    ui->listFiles->clear();
//    ui->listFiles->addItem("=======共享文件======");
//    foreach (const QJsonValue &v, files) {
//        QJsonObject obj = v.toObject();

//        // 客户端代码修正
//        QString filename = obj["name"].toString();
//        int filesize = obj["size"].toInt();
//        Q_UNUSED(filesize);
//        QListWidgetItem *item = new QListWidgetItem(
//            QString("%1 (%2 KB)").arg(obj["name"].toString()).arg(obj["size"].toInt()/1024)
//        );
//        qDebug()<<"添加  文件 "<<filename;
//        item->setData(Qt::UserRole,filename); // 存储真实文件名
//        ui->listFiles->addItem(item);
//    }
//}
void MainWindow::onFileListReceived(const QJsonArray &files) {
    ui->listFiles->clear();
    foreach (const QJsonValue &v, files) {
        QJsonObject obj = v.toObject();
        QString name = obj["name"].toString();
        int size = obj["size"].toInt();

        QListWidgetItem *item = new QListWidgetItem(
            QString("%1 (%2 KB)").arg(name).arg(size / 1024)
        );
        item->setData(Qt::UserRole, name);
        ui->listFiles->addItem(item);
    }
}
void MainWindow::onFileUploadSuccess()
{
    QMessageBox::information(this, "上传成功", "文件已成功上传至服务器");
    refreshFileList();
}
void MainWindow::refreshFileList()
{
    MessagePackage pack;
    pack.setType("file_list_req");
    MessagePackage::sendMessage(pack, socket); // 使用现有消息发送机制
}
// 文件数据接收槽函数
// mainwindow.cpp
void MainWindow::onFileDataReceived(const QString &savePath, const QByteArray &data) {
    QFile file(savePath); // 直接使用完整路径
    if (file.open(QIODevice::WriteOnly)) {
        file.write(data);
        file.close();
        QMessageBox::information(this, "下载完成", "文件已保存到：" + savePath);
    } else {
        QMessageBox::critical(this, "错误", "文件保存失败：" + file.errorString());
    }
}
//void MainWindow::onFileDataReceived(const QString &filename, const QByteArray &data){
//    QFile file(filename);
//    if(file.open(QIODevice::WriteOnly)){
//        file.write(data);
//        file.close();
//        QMessageBox::information(this, "下载完成", "文件已保存到本地");
//    }

//}

void MainWindow::on_send_pb_clicked()
{
//    ui->recv_w->hide();
//    ui->horizontalSlider->show();
//    chandler = new cameraHandler(this);
//    sender = new videoSender(this);
//    connect(chandler,&cameraHandler::videoUpdated,this,&MainWindow::on_videoUpdated);
//    connect(chandler,&cameraHandler::sendVideo,sender,&videoSender::sendeVideo);
}

void MainWindow::on_recv_pb_clicked()
{
//    ui->send_w->hide();
//    recver = new videoRecver;
//    thread = new QThread(this);
//    recver->moveToThread(thread);
//    connect(thread,&QThread::started,recver,&videoRecver::onReadyRead);
//    connect(thread,&QThread::finished,recver,&videoRecver::endTask);

//    connect(recver,&videoRecver::recvComplete,this,&MainWindow::videoSet,Qt::BlockingQueuedConnection);

//    thread->start();
}
void MainWindow::on_videoUpdated(QImage image)
{
    QPixmap picture = QPixmap::fromImage(image); //从QImage图片对象转成QPixmap格式图片对象
    ui->send_w->setPixmap(picture);
}


void MainWindow::on_horizontalSlider_valueChanged(int value)
{
    chandler->setImageQuality(value);
}
void MainWindow::videoSet(QImage image)
{
    if(image.isNull())
    {
        return;
    }

    image = image.scaled(ui->recv_w->width(),ui->recv_w->height(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
    QPixmap picture = QPixmap::fromImage(image); //从QImage图片对象转成QPixmap格式图片对象
    qDebug()<<image.size()<<picture.size();
    ui->recv_w->setPixmap(picture);
}
void MainWindow::createMeeting()
{
    socketHelper::getInstance()->createMeeting();
}

void MainWindow::joinMeeting()
{
    QString meetingId = ui->lineEdit_meetingId->text();
    socketHelper::getInstance()->joinMeeting(meetingId);
}
void MainWindow::onMeetingCreated(MessagePackage ipport_pack)
{
    audioSender = new AudioSender(ipport_pack.multicastIp(), ipport_pack.multicastPort() + 1); // 用不同端口
    audioSender->start();

    ui->horizontalSlider->show();
    ui->label_meetingStatus->setText("会议已创建: " + ipport_pack.meetingId());
    qDebug()<<ipport_pack.multicastIp()<<ipport_pack.multicastPort()<<"该会议 要绑定的 ip和端口";
    this->my_videoSender = new videoSender(ipport_pack.multicastIp(),ipport_pack.multicastPort(),this);
    chandler = new cameraHandler(this);
    connect(chandler,&cameraHandler::videoUpdated,this,&MainWindow::on_videoUpdated);
    connect(chandler,&cameraHandler::sendVideo,this->my_videoSender,&videoSender::sendeVideo);


}
void MainWindow::onMeetingJoined(MessagePackage pack)
{
    audioRecver = new AudioRecver(pack.multicastIp(), pack.multicastPort() + 1);
    audioRecver->start();

    ui->label_meetingStatus->setText("已加入会议: " + pack.meetingId());
    recver = new videoRecver(pack.multicastIp(),pack.multicastPort());
    thread = new QThread(this);
    recver->moveToThread(thread);
    connect(thread,&QThread::started,recver,&videoRecver::onReadyRead);
    connect(thread,&QThread::finished,recver,&videoRecver::endTask);
    connect(recver,&videoRecver::recvComplete,this,&MainWindow::videoSet,Qt::BlockingQueuedConnection);
    thread->start();


}
